package com.java.gui;

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ItemEventTest extends JFrame {
	private JLabel provinceLabel,cityLabel;
	private JComboBox provinceComboBox,cityComboBox;
	private String[] pro;
	private String[][] cities;
	public ItemEventTest(String[] pro,String[][] cities){
		super("下拉列表框测试");
		this.pro=pro;
		this.cities=cities;
		this.provinceLabel=new JLabel("省份:");
		this.cityLabel=new JLabel("城市:");
		provinceComboBox=new JComboBox(pro);
		cityComboBox=new JComboBox(cities[0]);//cities[0]
		this.setLayout(new FlowLayout());
		this.add(this.provinceLabel);
		this.add(this.provinceComboBox);
		this.add(this.cityLabel);
		add(cityComboBox);
	}
	public void showMe(){
		addEventHandler();
		this.setSize(300, 200);
		setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public void addEventHandler(){
		provinceComboBox.addItemListener(new ItemListener(){

			public void itemStateChanged(ItemEvent e) {
				int index=ItemEventTest.this.provinceComboBox.getSelectedIndex();
//				cityComboBox.removeAll();
				cityComboBox.removeAllItems();
				for(int i=0;i<cities[index].length;i++){
					cityComboBox.addItem(cities[index][i]);
				}
			}
			
		});
	}
	public static void main(String[] args){
		String[] pro={"江西","江苏","浙江","福建"};
		String[][] cities={{"南昌","上饶","抚州","宜春"},{"南京","连云港","苏州","扬州"},{"杭州","绍兴","嘉兴","义乌"},{"福州","厦门","泉州","南平"}};
		new ItemEventTest(pro,cities).showMe();
	}

}
